package com.chen.net;

import com.chen.pojo.NetInfoVo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Arrays;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/15 02:05
 */
@Slf4j
public class SocketGroup {
    private static NetInfoVo netInfoVo;

    public static final String uuid = UUID.randomUUID().toString();

    private static InetAddress inetAddress;
    private static MulticastSocket socket;

    public SocketGroup(NetInfoVo netInfoVo) throws IOException {
        this.netInfoVo = netInfoVo;
        inetAddress = InetAddress.getByName(netInfoVo.getSocketIp());
        socket = new MulticastSocket(netInfoVo.getSocketPort());
        socket.joinGroup(inetAddress);
    }

    public void initListener(ReceiveListener receiveListener) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                DatagramPacket inPacket;
                while (true) {
                    try {
                        int socketMaxLength = Integer.valueOf(netInfoVo.getSocketMaxLength());
                        byte[] inBuff = new byte[socketMaxLength];
                        inPacket = new DatagramPacket(inBuff, inBuff.length);
                        socket.receive(inPacket);
                        String message = new String(Arrays.copyOf(inPacket.getData(), inPacket.getLength()), "utf-8");
                        receiveListener.receiveed(message);
                    } catch (Exception e) {
                    }
                }
            }
        }.start();
    }

    public void sendMsg(String message) throws IOException {
        byte[] msgBytes = message.getBytes("utf-8");
        DatagramPacket sender = new DatagramPacket(msgBytes, msgBytes.length, inetAddress, netInfoVo.getSocketPort());
        socket.send(sender);
    }
}
